package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.hjq.http.listener.HttpCallback;
import com.hjq.umeng.UmengClient;
import com.qiantu.api.entity.SmsBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.aop.SingleClick;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.app.AppConfig;
import com.qiantu.phone.other.KeyboardWatcher;
import com.qiantu.phone.utils.StringUtil;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class EnterNewPhoneActivity extends AppActivity
        implements KeyboardWatcher.SoftKeyboardStateListener,
        TextView.OnEditorActionListener {

    private String originalSmsId;
    private String oldPhone;

    @Log
    public static void start(Context context, String oldPhone, String originalSmsId, int type) {
        Intent intent = new Intent(context, EnterNewPhoneActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("oldPhone", oldPhone);
        intent.putExtra("originalSmsId", originalSmsId);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Log
    public static void start(Context context, String oldPhone, String description, String accountInfo, int type) {
        Intent intent = new Intent(context, EnterNewPhoneActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("oldPhone", oldPhone);
        intent.putExtra("description", description);
        intent.putExtra("accountInfo", accountInfo);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    private EditText editNewPhone;
    private TextView mNewPhoneErrorHint;
    private View btnNext;
    private int type;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_enter_new_phone;
    }

    @Override
    protected void initView() {
        UmengClient.init(AppApplication.getInstance(), AppConfig.isLogEnable());
        type = getInt("type");
        originalSmsId = getString("originalSmsId");
        oldPhone = getString("oldPhone");
        btnNext = findViewById(R.id.btn_next);
        editNewPhone = findViewById(R.id.edit_new_phone);
        mNewPhoneErrorHint = findViewById(R.id.tv_new_phone_error_hint);
        setOnClickListener(btnNext);
        editNewPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() == 11){
                    btnNext.setEnabled(true);
                }else{
                    btnNext.setEnabled(false);
                }
            }
        });
    }

    @Override
    protected void initData() {
        postDelayed(() -> {
            KeyboardWatcher.with(EnterNewPhoneActivity.this)
                    .setListener(EnterNewPhoneActivity.this);
        }, 500);
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_next:
                getCode();
                break;
        }
    }

    private void getCode(){
        String phone = editNewPhone.getText().toString();
        if (!StringUtil.isPhoneLegal(phone)) {
            editNewPhone.setSelected(true);
            mNewPhoneErrorHint.setText(R.string.phone_error_hint);
            return;
        }
        editNewPhone.setSelected(false);
        if(phone.equals(oldPhone)){
            toast(R.string.new_phone_equal_old_phone);
            return;
        }
        showDialog();
        Map<String, Object> data = new HashMap<>();
        data.put("mobile", phone);
        // 隐藏软键盘
        hideKeyboard(getCurrentFocus());
        switch (type){
            case 1://提交申诉
                LLHttpManager.aftersalesSendSms(this, data, new HttpCallback<HttpData<SmsBean>>(this){
                    @Override
                    public void onStart(Call call) {
                    }

                    @Override
                    public void onEnd(Call call) {
                        hideDialog();
                    }

                    @Override
                    public void onSucceed(HttpData<SmsBean> data) {
                        if(data.isRequestSucceed()){
                            toast(R.string.sms_code_send);
                            postDelayed(() -> {
                                // 跳转到验证码界面
                                //手机号不可用，新手机获取验证码
                                String oldPhone = getIntent().getStringExtra("oldPhone");
                                String description = getIntent().getStringExtra("description");
                                String accountInfo = getIntent().getStringExtra("accountInfo");
                                Captcha1Activity.start(EnterNewPhoneActivity.this, editNewPhone.getText().toString(), oldPhone, description, accountInfo, data.getData().getSmsID(), 1);
                            }, 600);
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });
                break;
            case 2://验证手机号后，完成更换
                data.put("smsType", "changeMobile2_boyun");
                LLHttpManager.sendSms(this, data, new HttpCallback<HttpData<SmsBean>>(this){
                    @Override
                    public void onStart(Call call) {
                    }

                    @Override
                    public void onEnd(Call call) {
                        hideDialog();
                    }

                    @Override
                    public void onSucceed(HttpData<SmsBean> data) {
                        if(data.isRequestSucceed()){
                            toast(R.string.sms_code_send);
                            postDelayed(() -> {
                                // 跳转到验证码界面
                                //新手机获取验证码后，传入新smsId
                                Captcha1Activity.start(EnterNewPhoneActivity.this, editNewPhone.getText().toString(), originalSmsId, data.getData().getSmsID(),3);
                            }, 600);
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 友盟回调
        UmengClient.onActivityResult(this, requestCode, resultCode, data);
    }

    /**
     * {@link KeyboardWatcher.SoftKeyboardStateListener}
     */

    @Override
    public void onSoftKeyboardOpened(int keyboardHeight) {
        // 执行位移动画
    }

    @Override
    public void onSoftKeyboardClosed() {
        // 执行位移动画
    }

    /**
     * {@link TextView.OnEditorActionListener}
     */
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE && editNewPhone.isEnabled()) {
            // 模拟点击登录按钮
//            onClick(mCommitView);
            return true;
        }
        return false;
    }
}